<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>成绩管理 - 教学管理系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            background-color: #2c3e50;
            color: white;
            padding-top: 20px;
        }

        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid #3c5166;
        }

        .sidebar-header h2 {
            margin: 0;
            font-size: 20px;
        }

        .user-info {
            margin-top: 10px;
            font-size: 14px;
            opacity: 0.8;
        }

        .menu-section {
            padding: 10px 20px;
            font-size: 14px;
            color: rgba(255, 255, 255, 0.6);
            border-bottom: 1px solid #3c5166;
            margin-top: 15px;
        }

        .menu {
            list-style: none;
            padding: 0;
            margin: 20px 0;
        }

        .menu li {
            padding: 12px 20px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .menu li:hover {
            background-color: #3c5166;
        }

        .menu li.active {
            background-color: #3498db;
        }

        .menu a {
            color: white;
            text-decoration: none;
            display: block;
        }

        .content {
            flex: 1;
            padding: 20px;
        }

        .content-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
        }

        .content-header h1 {
            margin: 0;
            color: #333;
            font-size: 24px;
        }

        .search-box {
            display: flex;
            width: 300px;
        }

        .search-box input {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px 0 0 4px;
            outline: none;
        }

        .search-box button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 0 4px 4px 0;
            cursor: pointer;
        }

        .batch-grade-button {
            background-color: #2ecc71;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background-color: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            table-layout: fixed;
        }

        th,
        td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        th {
            background-color: #f8f9fa;
            font-weight: bold;
            color: #333;
        }

        tr:hover {
            background-color: #f5f7f9;
        }

        .grade-cell {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .grade-input {
            width: 60px;
            text-align: center;
            padding: 4px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .actions {
            display: flex;
            justify-content: center;
            gap: 8px;
        }

        .edit-button {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            background-color: #3498db;
            color: white;
            width: auto;
            display: inline-block;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: white;
            margin: 10% auto;
            padding: 20px;
            border-radius: 8px;
            width: 50%;
            max-width: 500px;
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover {
            color: black;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }

        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .btn-cancel,
        .btn-save {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .btn-cancel {
            background-color: #f1f1f1;
            color: #333;
        }

        .btn-save {
            background-color: #2ecc71;
            color: white;
        }

        .filter-section {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            align-items: flex-end;
        }

        .filter-item {
            flex: 1;
        }

        .logout {
            margin-top: auto;
            padding: 20px;
        }

        .logout a {
            color: #e74c3c;
            text-decoration: none;
        }

        /* 设置列宽 */
        th:nth-child(1),
        td:nth-child(1) {
            width: 8%;
        }

        /* 选课ID */
        th:nth-child(2),
        td:nth-child(2) {
            width: 10%;
        }

        /* 学生ID */
        th:nth-child(3),
        td:nth-child(3) {
            width: 12%;
        }

        /* 学生姓名 */
        th:nth-child(4),
        td:nth-child(4) {
            width: 10%;
        }

        /* 课程ID */
        th:nth-child(5),
        td:nth-child(5) {
            width: 15%;
        }

        /* 课程名称 */
        th:nth-child(6),
        td:nth-child(6) {
            width: 15%;
        }

        /* 选课时间 */
        th:nth-child(7),
        td:nth-child(7) {
            width: 10%;
        }

        /* 成绩 */
        th:nth-child(8),
        td:nth-child(8) {
            width: 10%;
            text-align: center;
        }

        /* 操作 */
    </style>
</head>

<body>
    <div class="container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>教学管理系统</h2>
                <div class="user-info" th:if="${session.user}">
                    <span th:text="${session.user.username}">admin1</span> - 管理员
                </div>
            </div>
            <div class="menu-section">基础管理</div>
            <ul class="menu">
                <li><a href="/admin/dashboard">系统概览</a></li>
                <li><a href="/admin/teachers">教师管理</a></li>
                <li><a href="/admin/students">学生管理</a></li>
                <li><a href="/admin/courses">课程管理</a></li>
                <li><a href="/admin/classrooms">教室管理</a></li>
            </ul>

            <div class="menu-section">教务管理</div>
            <ul class="menu">
                <li><a href="/admin/course-selections">选课管理</a></li>
                <li class="active"><a href="/admin/grades">成绩管理</a></li>
            </ul>

            <div class="menu-section">系统设置</div>
            <ul class="menu">
                <li><a href="/admin/profile">个人信息</a></li>
            </ul>

            <div class="logout">
                <a href="/logout">退出登录</a>
            </div>
        </div>

        <div class="content">
            <div class="content-header">
                <h1>成绩管理</h1>
                <div class="search-box">
                    <input type="text" id="searchInput" placeholder="搜索学生ID或姓名...">
                    <button type="button" onclick="searchGrades()">搜索</button>
                </div>
                <button class="batch-grade-button" onclick="saveBatchGrades()">批量保存成绩</button>
            </div>

            <div class="filter-section">
                <div class="filter-item">
                    <label for="studentFilter">按学生筛选</label>
                    <select id="studentFilter" onchange="filterByStudent()">
                        <option value="">所有学生</option>
                        <!-- 学生选项将通过JavaScript动态加载 -->
                    </select>
                </div>
                <div class="filter-item">
                    <label for="courseFilter">按课程筛选</label>
                    <select id="courseFilter" onchange="filterByCourse()">
                        <option value="">所有课程</option>
                        <!-- 课程选项将通过JavaScript动态加载 -->
                    </select>
                </div>
            </div>

            <table id="gradesTable">
                <thead>
                    <tr>
                        <th>选课ID</th>
                        <th>学生ID</th>
                        <th>学生姓名</th>
                        <th>课程ID</th>
                        <th>课程名称</th>
                        <th>选课时间</th>
                        <th>成绩</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="gradesList">
                    <!-- 数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 编辑成绩模态框 -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeEditModal()">&times;</span>
            <h2>编辑成绩</h2>
            <input type="hidden" id="editSelectionId">
            <div class="form-group">
                <label for="editStudentInfo">学生</label>
                <input type="text" id="editStudentInfo" readonly>
            </div>
            <div class="form-group">
                <label for="editCourseInfo">课程</label>
                <input type="text" id="editCourseInfo" readonly>
            </div>
            <div class="form-group">
                <label for="editGrade">成绩</label>
                <input type="number" id="editGrade" name="grade" min="0" max="100" step="0.5">
            </div>
            <div class="form-actions">
                <button class="btn-cancel" onclick="closeEditModal()">取消</button>
                <button class="btn-save" onclick="updateGrade()">保存</button>
            </div>
        </div>
    </div>

    <script>
        // 存储所有成绩记录的数据
        let allGrades = [];
        // 存储已修改但未保存的成绩
        const modifiedGrades = {};

        // 页面加载时获取所有成绩记录
        document.addEventListener('DOMContentLoaded', function () {
            fetchGrades();
            fetchStudents();
            fetchCourses();
        });

        // 获取所有成绩记录
        function fetchGrades() {
            fetch('/api/admin/grades')
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        }
                        throw new Error('获取成绩记录失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    allGrades = data;
                    renderGradesList(data);
                })
                .catch(error => {
                    console.error('获取成绩记录出错:', error);
                });
        }

        // 获取所有学生
        function fetchStudents() {
            fetch('/api/admin/students')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取学生失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    populateStudentOptions(data);
                })
                .catch(error => {
                    console.error('获取学生出错:', error);
                });
        }

        // 获取所有课程
        function fetchCourses() {
            fetch('/api/admin/courses')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取课程失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    populateCourseOptions(data);
                })
                .catch(error => {
                    console.error('获取课程出错:', error);
                });
        }

        // 填充学生选项
        function populateStudentOptions(students) {
            const studentFilter = document.getElementById('studentFilter');

            // 清空现有选项（保留第一个"所有学生"选项）
            studentFilter.innerHTML = '<option value="">所有学生</option>';

            students.forEach(student => {
                const option = document.createElement('option');
                option.value = student.studentId;
                option.textContent = `${student.name} (${student.studentId})`;

                studentFilter.appendChild(option);
            });
        }

        // 填充课程选项
        function populateCourseOptions(courses) {
            const courseFilter = document.getElementById('courseFilter');

            // 清空现有选项（保留第一个"所有课程"选项）
            courseFilter.innerHTML = '<option value="">所有课程</option>';

            courses.forEach(course => {
                const option = document.createElement('option');
                option.value = course.courseId;
                option.textContent = `${course.name} (${course.courseId})`;

                courseFilter.appendChild(option);
            });
        }

        // 渲染成绩记录列表
        function renderGradesList(grades) {
            const tableBody = document.getElementById('gradesList');
            tableBody.innerHTML = '';

            if (grades.length === 0) {
                const emptyRow = document.createElement('tr');
                emptyRow.innerHTML = '<td colspan="8" style="text-align: center;">没有找到成绩记录</td>';
                tableBody.appendChild(emptyRow);
                return;
            }

            grades.forEach(grade => {
                const row = document.createElement('tr');

                // 检查是否有未保存的修改
                const gradeValue = modifiedGrades[grade.selectionId] !== undefined
                    ? modifiedGrades[grade.selectionId]
                    : grade.score;

                // 提取学生和课程的名称
                const studentName = grade.student ? grade.student.name : '未知';
                const courseName = grade.course ? grade.course.name : '未知';
                const selectionTime = grade.year + '年 ' + grade.semester;

                row.innerHTML = `
                    <td>${grade.selectionId}</td>
                    <td>${grade.studentId}</td>
                    <td>${studentName}</td>
                    <td>${grade.courseId}</td>
                    <td>${courseName}</td>
                    <td>${selectionTime}</td>
                    <td>
                        <input type="number" class="grade-input" 
                            value="${gradeValue !== null ? gradeValue : ''}" 
                            min="0" max="100" step="0.5" 
                            onchange="handleGradeChange(${grade.selectionId}, this.value)" 
                            placeholder="未评分">
                    </td>
                    <td class="actions">
                        <button class="edit-button" onclick="openEditModal(${grade.selectionId})">编辑</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
        }

        // 处理成绩输入变化
        function handleGradeChange(selectionId, value) {
            if (value === '') {
                modifiedGrades[selectionId] = null;
            } else {
                const numValue = parseFloat(value);
                if (!isNaN(numValue)) {
                    modifiedGrades[selectionId] = numValue;
                }
            }
        }

        // 批量保存成绩
        function saveBatchGrades() {
            if (Object.keys(modifiedGrades).length === 0) {
                alert('没有需要保存的成绩修改');
                return;
            }

            const gradesData = Object.entries(modifiedGrades).map(([selectionId, grade]) => {
                return { selectionId: parseInt(selectionId), grade: grade };
            });

            fetch('/api/admin/grades/batch', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(gradesData)
            })
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        }
                        return response.text().then(text => { throw new Error(text || '批量更新成绩失败') });
                    }
                    return response.text();
                })
                .then(() => {
                    alert('批量更新成绩成功');
                    // 清空修改记录
                    for (const selectionId in modifiedGrades) {
                        // 更新allGrades中的成绩
                        const grade = allGrades.find(g => g.selectionId === parseInt(selectionId));
                        if (grade) {
                            grade.score = modifiedGrades[selectionId];
                        }
                    }
                    // 清空修改记录
                    Object.keys(modifiedGrades).forEach(key => delete modifiedGrades[key]);
                    // 重新渲染表格
                    renderGradesList(allGrades);
                })
                .catch(error => {
                    console.error('批量更新成绩出错:', error);
                });
        }

        // 格式化日期时间
        function formatDateTime(dateTimeStr) {
            if (!dateTimeStr) return '未记录';
            const date = new Date(dateTimeStr);
            return date.toLocaleString('zh-CN');
        }

        // 搜索成绩记录
        function searchGrades() {
            const searchTerm = document.getElementById('searchInput').value.trim();
            if (searchTerm === '') {
                fetchGrades();
                return;
            }

            fetch(`/api/admin/grades/search?term=${encodeURIComponent(searchTerm)}`)
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        }
                        throw new Error('搜索成绩记录失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    allGrades = data;
                    renderGradesList(data);
                })
                .catch(error => {
                    console.error('搜索成绩记录出错:', error);
                });
        }

        // 按学生筛选
        function filterByStudent() {
            const studentId = document.getElementById('studentFilter').value;
            if (studentId === '') {
                fetchGrades();
                return;
            }

            fetch(`/api/admin/grades/search?studentId=${encodeURIComponent(studentId)}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('筛选成绩记录失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    allGrades = data;
                    renderGradesList(data);
                })
                .catch(error => {
                    console.error('筛选成绩记录出错:', error);
                });
        }

        // 按课程筛选
        function filterByCourse() {
            const courseId = document.getElementById('courseFilter').value;
            if (courseId === '') {
                fetchGrades();
                return;
            }

            fetch(`/api/admin/grades/search?courseId=${encodeURIComponent(courseId)}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('筛选成绩记录失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    allGrades = data;
                    renderGradesList(data);
                })
                .catch(error => {
                    console.error('筛选成绩记录出错:', error);
                });
        }

        // 打开编辑成绩模态框
        function openEditModal(selectionId) {
            const grade = allGrades.find(g => g.selectionId === selectionId);
            if (!grade) {
                alert('找不到成绩记录');
                return;
            }

            document.getElementById('editSelectionId').value = grade.selectionId;
            document.getElementById('editStudentInfo').value = `${grade.student ? grade.student.name : grade.studentId} (${grade.studentId})`;
            document.getElementById('editCourseInfo').value = `${grade.course ? grade.course.name : grade.courseId} (${grade.courseId})`;

            // 设置当前成绩，优先使用未保存的修改
            const currentGrade = modifiedGrades[grade.selectionId] !== undefined
                ? modifiedGrades[grade.selectionId]
                : grade.score;
            document.getElementById('editGrade').value = currentGrade !== null ? currentGrade : '';

            document.getElementById('editModal').style.display = 'block';
        }

        // 关闭编辑成绩模态框
        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        // 更新成绩
        function updateGrade() {
            const selectionId = document.getElementById('editSelectionId').value;
            const gradeValue = document.getElementById('editGrade').value.trim();

            const gradeData = {
                grade: gradeValue === '' ? null : parseFloat(gradeValue)
            };

            fetch(`/api/admin/grades/${selectionId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(gradeData)
            })
                .then(response => {
                    if (!response.ok) {
                        if (response.status === 401) {
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        } else if (response.status === 404) {
                            alert('成绩记录不存在');
                        }
                        return response.text().then(text => { throw new Error(text || '更新成绩失败') });
                    }
                    return response.json();
                })
                .then(data => {
                    alert('更新成绩成功');
                    closeEditModal();

                    // 更新本地数据
                    const grade = allGrades.find(g => g.selectionId === parseInt(selectionId));
                    if (grade) {
                        grade.score = data.score;
                    }

                    // 如果有未保存的修改，删除它
                    if (modifiedGrades[selectionId] !== undefined) {
                        delete modifiedGrades[selectionId];
                    }

                    renderGradesList(allGrades);
                })
                .catch(error => {
                    console.error('更新成绩出错:', error);
                });
        }
    </script>
</body>

</html>